﻿#include "FComboBox.h"
#include "../Base/FTheme.h"

#include <QProxyStyle>
#include <QPainterPath>
#include <QPainter>
#include <QApplication>
#include <QListView>


FComboBox::FComboBox(QWidget *parent)
    : QComboBox(parent)
    , m_anim(new QPropertyAnimation(this, "arrowAngle"))
{
    setView(new QListView(this));

    QString qss = QString(R"(
FComboBox {
    border: 1px solid %1;
    border-radius: 4px;
    padding: 4px;
    background: %5;
}
FComboBox:hover {
    border: 1px solid %2;
}
FComboBox:focus {
    border: 1px solid %3;
}
FComboBox:disabled {
    background: 1px solid %4;
}
FComboBox::down-arrow {
    border: none;
}
FComboBox::drop-down {
    width: 20px;
    border: none;
}
)").arg(FColors::getBaseColor(FColors::Default).name(QColor::HexArgb),
        FColors::getHoverColor(FColors::Default).name(QColor::HexArgb),
        FColors::getActiveColor(FColors::Default).name(QColor::HexArgb),
        FColors::getDisabledColor(FColors::Default).name(QColor::HexArgb),
        FColors::getBackgroundColor().name(QColor::HexArgb));

    setStyleSheet(qss);
    setContextMenuPolicy(Qt::CustomContextMenu);
}

qreal FComboBox::arrowAngle() const
{
    return m_angle;
}

void FComboBox::setArrowAngle(qreal v)
{
    m_angle = v;
    update();
}

void FComboBox::showPopup()
{
    animateTo(180); // 展开 → ▼ 旋到 ∧
    QComboBox::showPopup();
}

void FComboBox::hidePopup()
{
    animateTo(0); // 收起 → ∧ 旋回 ▼
    QComboBox::hidePopup();
}

void FComboBox::paintEvent(QPaintEvent *event)
{
    // 先绘制文本和背景
    QComboBox::paintEvent(event);

    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing, true);

    const int arrowAreaWidth = 20;        // 右侧固定区域宽度
    QRect area(width() - arrowAreaWidth, 0, arrowAreaWidth, height());

    // 箭头尺寸：占高度 40%（更协调）
    int s = height() * 0.4;

    // 箭头绘制区域（水平垂直居中）
    QRect arrowRect(
        area.center().x() - s / 2,
        area.center().y() - s / 3,
        s,
        s
        );

    // 绘制三角形两条边：
    p.save();
    p.translate(arrowRect.center());
    p.rotate(m_angle);
    p.setRenderHint(QPainter::Antialiasing, true);

    qreal half = s * 0.35;
    qreal h = s * 0.2;

    QPen pen(FColors::getHoverColor(FColors::Default), 2);
    p.setPen(pen);

    // 左腰
    p.drawLine(QPointF(-half, -s * 0.2), QPointF(0, h));
    // 右腰
    p.drawLine(QPointF( half, -s * 0.2), QPointF(0, h));

    p.restore();

/*
    // 绘制填充三角形：
    // 平移 + 旋转
    p.translate(arrowRect.center());
    p.rotate(m_angle);

    // 绘制三角 ▼
    QPainterPath path;
    path.moveTo(-s * 0.5, -s * 0.35);
    path.lineTo( s * 0.5, -s * 0.35);
    path.lineTo( 0,        s * 0.45 );
    path.closeSubpath();

    p.fillPath(path, FColors::getHoverColor(FColors::Default));
*/
}

void FComboBox::animateTo(qreal target)
{
    m_anim->setDuration(150);
    m_anim->setStartValue(m_angle);
    m_anim->setEndValue(target);
    m_anim->setEasingCurve(QEasingCurve::InOutCubic);
    m_anim->start();
}
